﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NewsCollection.Common.Service
{
    public static class Extensions
    {
        const int width = 150;
        const int height = 150;
       public  enum AnchorPosition
        {
            Top,
            Center,
            Bottom,
            Left,
            Right
        }
        public static string ToCutString(this object obj)
        {
            String s = obj.ToString();
            if (s.Contains("\n") || s.Contains("\t"))
            {
                s.Replace("\n", "");
                s.Replace("\t", "");


            }
            if (s.Contains('\"'))
            {
                string[] a = s.Split('\"');
                s = a[1].ToString();
            }
            if (s.IndexOf("-") >= 0)
            {
                s.Remove(s.IndexOf("-"), 1);
            }

            return s.Replace("-", " ").Replace("&quot;", "").Replace("&nbsp;", "")
                .Replace("\r", "").Replace("\n", "").Replace("'","").Replace("?","").
                Replace(",","").Replace(":","").Replace("%","").Replace("&#","").Replace(";","").Trim();
        }
        // convert co dau sang khong dau
        public static string convertToUnSign3(this object obj)
        {
            Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string s = obj.ToString();
            string temp = s.Normalize(NormalizationForm.FormD);

            return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D').Replace(" ", "-");

        }
        // check chuoi la so 
        public static bool IsNumber(this object obj)
        {
            string pValue = obj.ToString();
            foreach (Char c in pValue)
            {
                if (!Char.IsDigit(c))
                    return false;
            }
            return true;
        }
        public static string GetDateInString(this object obj)
        {

            string pValue = obj.ToString().Trim();
            if(pValue.Contains(","))
            {
                if (pValue.Contains("ngày") && pValue.Contains("tháng") && pValue.Contains("năm"))
                {
                    //pValue.Trim().Replace(" ","");
                    string[] s = pValue.Split(' ');
                    string ngay = "";
                    string thang = "";
                    string nam = "";
                    string[] listStringThang = { "một", "hai", "ba", "tư", "năm", "sáu", "bảy", "tám", "chín", "mười", "mười một", "mười hai" };
                    string[] listIntThang = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
                    for (int i = 0; i < s.Count(); i++)
                    {
                        if (s[i].Equals("ngày"))
                        {
                            ngay = s[i + 1];
                        }
                        if (s[i].Equals("tháng"))
                        {
                            thang = s[i + 1];
                        }
                        if (s[i].Equals("năm"))
                        {
                            nam = s[i + 1];
                        }
                        if (ngay != "" && thang != "" && nam != "")
                        {
                            break;
                        }
                    }
                    for (int i = 0; i < listStringThang.Count(); i++)
                    {
                        if (listStringThang[i].Equals(thang))
                        {
                            thang = listIntThang[i];
                        }
                    }
                    //string ngay = pValue.Substring(pValue.IndexOf("ngày"), pValue.IndexOf("tháng"));
                    //string thang = pValue.Substring(pValue.IndexOf("tháng"), pValue.IndexOf("năm"));
                    //string nam = pValue.Substring(pValue.IndexOf("năm"), pValue.Count()-1);
                    //  pValue = "";
                    pValue = ngay + "/" + thang + "/" + nam;
                }else 
                pValue= pValue.Split(' ')[2];

            }
            if (pValue.Contains("phút"))
            {

                //string[] s = pValue.Split(' ');
                //string phut = "";
                //for (int i = 0; i < s.Count(); i++)
                //{
                //    if (s[i].Equals("phút"))
                //    {
                //        phut = s[i - 1];
                //    }

                //}
                pValue = DateTime.Today + "";
            }
            else
                if (pValue.Contains("giờ") )
            {
                string[] s = pValue.Split(' ');
                string gio="";
                for (int i = 0; i < s.Count(); i++)
                {
                    if(s[i].Equals("giờ"))
                    {
                        gio = s[i - 1];
                    }

                }
                int nGio = Convert.ToInt32(gio);
                if (DateTime.Now.Hour >= nGio)
                    pValue = DateTime.Today + "";
                else
                    pValue = DateTime.Today.AddDays(-1)+"";
            }
            
             
                else 
                    if (pValue.Contains("-"))
                {
                    string[] s = pValue.Split('-');

                    pValue = s[1];
                }

                else
                        if (pValue.Contains("ngày"))
                {
                    pValue = pValue.Replace("ngày", "-");

                    string[] s = pValue.Split('-');

                    pValue = s[1];
                }

            return pValue.Trim();
        }

        //chuyen hinh sang nhi phan
        public static byte[] ImageToByteArrayFromFilePath(this object obj)
        {
            string imagefilePath = obj.ToString();
            byte[] imageArray = File.ReadAllBytes(imagefilePath);
            return imageArray;
        }
        public static Boolean CheckUrlHaveUrl(this object obj, string urlCheck)
        {
            string url = obj.ToString();
            if (url.Contains(urlCheck))
                return true;
            return false;
        }

        //public static byte[] getImageFromUrl(this object obj)
        //{

        //    string url = obj.ToString();
        //    System.Net.HttpWebRequest request = null;
        //    System.Net.HttpWebResponse response = null;
        //    byte[] b = null;

        //    request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
        //    request.KeepAlive = false;
        //    Random r = new Random();
        //    int time = r.Next(0, 10000);

        //    System.Threading.Thread.Sleep(time);
        //    request.Timeout = 15 * 1000;
        //    request.ReadWriteTimeout = 15 * 1000;

        //    response = (System.Net.HttpWebResponse)request.GetResponse();

        //    if (request.HaveResponse)
        //    {
        //        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        //        {
        //            Stream receiveStream = response.GetResponseStream();
        //            using (BinaryReader br = new BinaryReader(receiveStream))
        //            {
        //                b = br.ReadBytes(500000);
        //                br.Close();
        //            }
        //        }
        //    }

        //    return b;
        //}
        //public static Image ByteArrayToImage(this object obj)   
        //{
        //    byte[] byteArrayIn = (byte[])obj;
        //    MemoryStream ms = new MemoryStream(byteArrayIn);
        //    Image returnImage = Image.FromStream(ms);
        //    return returnImage;

        //}
        //public static Image BinaryToImage(byte[] binaryData)
        //{

        //    if (binaryData == null) return null;

        //    byte[] buffer = binaryData.ToArray();
        //    MemoryStream memStream = new MemoryStream();
        //    memStream.Write(buffer, 0, buffer.Length);
        //    return Image.FromStream(memStream);
        //}

        static public byte[] DownloadData(string Url)
        {
            string empty = string.Empty;
            return DownloadData(Url, out empty);
        }

        static public byte[] DownloadData(string Url, out string responseUrl)
        {
            byte[] downloadedData = new byte[0];
            Url = Url.Replace("//", "/").Replace(":/", "://");
            try
            {
                //Get a data stream from the url  
                WebRequest req = WebRequest.Create(Url);
                Random r = new Random();
                int time = r.Next(0, 10000);

                System.Threading.Thread.Sleep(time);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                responseUrl = response.ResponseUri.ToString();

                //Download in chuncks  
                byte[] buffer = new byte[1024];

                //Get Total Size  
                int dataLength = (int)response.ContentLength;

                //Download to memory  
                //Note: adjust the streams here to download directly to the hard drive  
                MemoryStream memStream = new MemoryStream();
                while (true)
                {
                    //Try to read the data  
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        //Write the downloaded data  
                        memStream.Write(buffer, 0, bytesRead);
                    }
                }

                //Convert the downloaded stream to a byte array  
                downloadedData = memStream.ToArray();

                //Clean up  
                stream.Close();
                memStream.Close();
            }
            catch (Exception)
            {
                responseUrl = string.Empty;
                return new byte[0];
            }

            return downloadedData;
        }
        
        public static Image ImageFromURL(string Url)
        {
            byte[] imageData = DownloadData(Url);
            //       ImageDetail imgDetail = new ImageDetail();
            Image img = null;

            try
            {
                MemoryStream stream = new MemoryStream(imageData);
                img = Image.FromStream(stream);
                

                stream.Close();
            }
            catch (Exception)
            {
            }

            return img;
        }
        //kiem tra hinh co width phu hop hay khong
        public static Boolean CheckImageWithWidth(byte[] imageData)
        {
           
            //       ImageDetail imgDetail = new ImageDetail();
            Image img = null;

            try
            {
                MemoryStream stream = new MemoryStream(imageData);
                img = Image.FromStream(stream);
                stream.Close();
                if (img.Width > width && img.Height> height)
                    return true;
            }
            catch (Exception)
            {
            }

            return false;
        }
        public static void SaveImageToFolder(this object obj, string folder)
        {
            if (obj != null)
            {
                Image img = (Image)obj;

                Bitmap b = new Bitmap(img);

                b.Save(@folder);
            }
         

        }
        //chuyen chuoi bi loi font
        public static String FixErrorText(this object obj)
        {
            string s = obj.ToString();
            string[] listError= {"226","224","234","236","250","39","244","243","249","232","242","225","193","237"};
            string[] listFix= {"â","à","ê","ì","ú","'","ô","ó","ù","è","ò","á","á","í"};
            var list  = s.Split(' ');
            string result = "";
            for (int i = 0; i < list.Count(); i++)
            {
                if( list[i].IsNumber() == false)
                for (int j = 0; j < listError.Count(); j++)
                {
                    if (list[i].Contains(listError[j]))
                    {
                   list[i]=list[i].Replace(listError[j], listFix[j]);

                    }
                }
               

            }
           


         for (int i = 0; i < list.Count(); i++)
         {
             result += list[i]+" ";
         }
           return result;

        }
        //check hinh url co chua .jpg hay khong  dau tien can lay
        public static Boolean CheckUrlFirstImage(this object obj)
        {
            string s = obj.ToString();

            if (s.Contains(".jpg") || s.Contains(".JPG"))
            {
                return true;
            }
            return false;
        }
        // convert byte to image
        public static Image ConvertByteToImage(byte[] imageData)
        {
            Image img = null;

            try
            {
                MemoryStream stream = new MemoryStream(imageData);
                img = Image.FromStream(stream);


                stream.Close();
            }
            catch (Exception)
            {
            }

            return img;
        }
        // resize anh

        public static Image ResizeImage(Image sourceImage, int maxWidth, int maxHeight)
        {
            //string url = Url.Replace("//", "/").Replace(":/", "://");
   //         Image sourceImage = ImageFromURL(url);
            //sourceImage = ConvertByteToImage(imageData);
            // Determine which ratio is greater, the width or height, and use
            // this to calculate the new width and height. Effectually constrains
            // the proportions of the resized image to the proportions of the original.
            double xRatio = (double)sourceImage.Width / maxWidth;
            double yRatio = (double)sourceImage.Height / maxHeight;
            double ratioToResizeImage = Math.Max(xRatio, yRatio);
            int newWidth = (int)Math.Floor(sourceImage.Width / ratioToResizeImage);
            int newHeight = (int)Math.Floor(sourceImage.Height / ratioToResizeImage);

            // Create new image canvas -- use maxWidth and maxHeight in this function call if you wish
            // to set the exact dimensions of the output image.
            Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);

            // Render the new image, using a graphic object
            using (Graphics newGraphic = Graphics.FromImage(newImage))
            {
                // Set the background color to be transparent (can change this to any color)
                newGraphic.Clear(Color.Transparent);

                // Set the method of scaling to use -- HighQualityBicubic is said to have the best quality
                newGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                // Apply the transformation onto the new graphic
                Rectangle sourceDimensions = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
                Rectangle destinationDimensions = new Rectangle(0, 0, newWidth, newHeight);
                newGraphic.DrawImage(sourceImage, destinationDimensions, sourceDimensions, GraphicsUnit.Pixel);
            }

            // Image has been modified by all the references to it's related graphic above. Return changes.
            return newImage;
        }
        // co dinh anh
        public static Image FixedSize(this object obj, int Width, int Height)
        {
            Image imgPhoto = (Image)obj;
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            //if we have to pad the height pad both the top and the bottom
            //with the difference between the scaled height and the desired height
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = (int)((Width - (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = (int)((Height - (sourceHeight * nPercent)) / 2);
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.White);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
        //crop anh
        public static Image Crop(this object obj, int Width, int Height, AnchorPosition Anchor)
        {
            Image imgPhoto = (Image)obj;
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(Height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((Height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(Width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((Width - (sourceWidth * nPercent)) / 2);
                        break;
                }
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
        public static Image MergeTwoImages(Image img1, Image img2)
        {
            int width = img1.Width + img2.Width;
            int height = Math.Max(img1.Height, img2.Height);

            Bitmap img3 = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(img3);
            g.DrawImage(img1, new Point(0, 0));
            g.DrawImage(img2, new Point(img1.Width, 0));

            g.Dispose();
            img1.Dispose();
            img2.Dispose();
            return (Image)img3;
        }
        public static Image ResizeImageFixedWidth( this object obj, int width)
        {
            Image imgToResize = (Image)obj;
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = ((float)width / (float)sourceWidth);

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.Clear(Color.Gainsboro);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (Image)b;
        }
    }
}
